package com.xatz.scanner

import android.app.AlertDialog
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.view.View
import android.view.WindowManager
import android.view.inputmethod.InputMethodManager
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.isGone
import androidx.core.view.isVisible
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.xatz.ksoap2_android.SoapEnvelope
import com.xatz.ksoap2_android.serialization.SoapObject
import com.xatz.ksoap2_android.serialization.SoapSerializationEnvelope
import com.xatz.ksoap2_android.transport.HttpTransportSE
import com.xatz.scanner.bean.CarDetailsCheckWeightBean
import com.xatz.scanner.bean.CheckWeightCarBean
import com.xatz.scanner.bean.ResultBean
import com.xatz.scanner.databinding.ActivityArrivalConfirmationDetailsBinding
import com.xatz.scanner.databinding.DialogCheckWeightLoadGoodsBinding
import com.xatz.scanner.databinding.DialogInvalidGrowthBinding
import com.xatz.scanner.databinding.ViewArrivalConfirmationBinding
import timber.log.Timber
import java.util.concurrent.Executors


/**
 * Created by tdq on 2022/1/4.
 */
class ArrivalConfirmationCheckWeightDetailsActivity : AppCompatActivity(), View.OnClickListener {

    private var mBinding: ActivityArrivalConfirmationDetailsBinding? = null

    private val mCarInfoBean by lazy { intent.getParcelableExtra("CheckWeightCarBean") as CheckWeightCarBean? }

    private var soCode = ""

    private val mThreadPool = Executors.newCachedThreadPool()

    private val netProgressDialog by lazy { NetProgressDialog(this) }

    private var mLists = mutableListOf<CarDetailsCheckWeightBean>()

    private val userAccount by lazy {
        getSharedPreferences(
            Constant.configName,
            Context.MODE_PRIVATE
        ).getString(Constant.userAccount, "").toString()
    }

    private val userBz: String by lazy {
        getSharedPreferences(
            Constant.configName,
            Context.MODE_PRIVATE
        ).getString(Constant.userBz, "").toString()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mBinding = ActivityArrivalConfirmationDetailsBinding.inflate(layoutInflater)
        setContentView(mBinding?.root)
        soCode = mCarInfoBean?.pcbm.toString()
        initData()
        mBinding?.btnInvalidGrowth?.setOnClickListener(this)
        mBinding?.btnLook?.setOnClickListener(this)
        mBinding?.toolbarLayout?.setRightViewOnClick(this)

        if (userBz == "TKB" || userBz == "GPB" || userBz == "KFB" || userBz == "GPK" || userBz == "TKY") {
            mBinding?.toolbarLayout?.rightText = "无效出厂"
        }

        initView()
    }

    private fun initView() {
        mBinding?.tvTimeText?.isGone = true
        mBinding?.tvTime?.isGone = true
        mBinding?.tvTimeLine?.isGone = true
        mBinding?.tvOrderStatusText?.isVisible = true
        mBinding?.tvOrderStatus?.isVisible = true
        mBinding?.tvTimeOrder?.isVisible = true
        mBinding?.tvOrderStatusLine?.isVisible = true
        mBinding?.tvActualProductNameText?.isVisible = true
        mBinding?.tvActualProductName?.isVisible = true
        mBinding?.tvActualSpecText?.isVisible = true
        mBinding?.tvActualSpec?.isVisible = true
        mBinding?.tvActualFurnaceText?.isVisible = true
        mBinding?.tvActualFurnace?.isVisible = true
        mBinding?.tvText?.text = "过磅信息及实提信息"
    }

    private fun showInputMethod() {
        val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS)
    }

    private fun initData() {
        netProgressDialog.showDialog()
        mThreadPool.submit {
            getCarInfoOnNet()
        }
    }

    private fun getCarInfoOnNet() {
        val method = "get_RuChangCLXX"
        val envolopeVersion = SoapEnvelope.VER11
        val soapAction = "http://tempuri.org/get_RuChangCLXX"
        val request = SoapObject(Constant.nameSpace, method)
        request.addProperty("pcbm", soCode)
        // SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
        val envelope = SoapSerializationEnvelope(envolopeVersion)
        envelope.setOutputSoapObject(request)
        envelope.dotNet = true
        val se = HttpTransportSE(Constant.urlCheckWeight)
        try {
            se.call(soapAction, envelope) //envolopeVersion为ver12第一个参数可以为空，必须接口支持ver12才行
            val response = envelope.bodyIn as SoapObject
            //response的处理需要根据返回的具体情况，基本都要进行下面一步
            Timber.e(response.toString())
            val responseSoapObject = response.getProperty("get_RuChangCLXXResult").toString()
            val checkWeightCarBeans = Gson().fromJson<List<CarDetailsCheckWeightBean>>(
                responseSoapObject,
                object : TypeToken<List<CarDetailsCheckWeightBean>>() {}.type
            )
            mLists = checkWeightCarBeans.toMutableList()
            runOnUiThread {
                netProgressDialog.dismiss()
                Timber.e(checkWeightCarBeans.size.toString())
                if (checkWeightCarBeans.isNotEmpty()) {
                    mBinding?.tvSoCode?.text = checkWeightCarBeans[0].pcbm
                    mBinding?.tvCarNumber?.text = checkWeightCarBeans[0].ksmc
                    mBinding?.tvDriverInfo?.text = checkWeightCarBeans[0].C11
                    mBinding?.tvTime?.text = checkWeightCarBeans[0].C11
                    mBinding?.tvOrderStatus?.text = checkWeightCarBeans[0].ckmc
                    mBinding?.tvRemark?.text = checkWeightCarBeans[0].bz

                    mBinding?.tvCarNum?.text = checkWeightCarBeans[0].clbm
//                    mBinding?.tvLoadLimit?.text = checkWeightCarBeans[0].C_XZ
                    mBinding?.tvTareTime?.text = checkWeightCarBeans[0].rcsj
                    mBinding?.tvTare?.text = checkWeightCarBeans[0].pz
                    mBinding?.tvActualProductName?.text = checkWeightCarBeans[0].stmc1
                    mBinding?.tvActualSpec?.text = checkWeightCarBeans[0].stgg1
                    mBinding?.tvActualFurnace?.text = checkWeightCarBeans[0].LH
                    if (checkWeightCarBeans[0].wxbz.isNotBlank()) {
                        mBinding?.toolbarLayout?.rightText = ""
                    }
                    for (i in checkWeightCarBeans.indices) {
                        val itemBinding = ViewArrivalConfirmationBinding.inflate(layoutInflater)
                        mBinding?.llContainer?.addView(itemBinding.root)
                        itemBinding.tvluhaoText.visibility = View.VISIBLE
                        itemBinding.tvluhaobz.visibility = View.VISIBLE
                        itemBinding.tvluhaobzLine.visibility = View.VISIBLE
                        itemBinding.tvluhao.visibility = View.VISIBLE
                        itemBinding.tvluhao1.visibility = View.VISIBLE
                        itemBinding.tvluhaoLine.visibility = View.VISIBLE
                        itemBinding.tvluhao1.text = checkWeightCarBeans[i].lh
                        itemBinding.tvluhao1.setOnClickListener {
                            val dialog = AlertDialog.Builder(this).create()
                            dialog.show()
                            val window = dialog.window
                            window?.clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM)
                            val dialogBinding =
                                DialogCheckWeightLoadGoodsBinding.inflate(layoutInflater)
                            window?.setContentView(dialogBinding.root)
                            dialogBinding.tvTypeText.setOnClickListener {
                                dialog.dismiss()
                                itemBinding.tvluhao1.text = "1#"
                            }
                            dialogBinding.tvRemarkText.setOnClickListener {
                                dialog.dismiss()
                                itemBinding.tvluhao1.text = "2#"
                            }
                        }

                        itemBinding.tvluhaobz.text =
                            Editable.Factory.getInstance().newEditable(checkWeightCarBeans[i].lhbz)
                        itemBinding.tvSoCode.text = checkWeightCarBeans[i].ckmc
                        itemBinding.tvDriverInfo.text = checkWeightCarBeans[i].cInvStd
//                        itemBinding.tvTime.text = checkWeightCarBeans[i].N_PLAN_CNT
                        itemBinding.tvWeight2.text = checkWeightCarBeans[i].szzl
                        itemBinding.tvOrderPerson.text = userAccount
                        checkWeightCarBeans[i].fhjs?.let {
                            itemBinding.tvOrderStatus.text =
                                Editable.Factory.getInstance().newEditable(it)
                        }

                        itemBinding.tvCarNumberText.text = "名称"
                        itemBinding.tvCarNumber.text = checkWeightCarBeans[i].chmc
                        itemBinding.tvCarNoLine.isGone = true
                        if (checkWeightCarBeans[i].fhjs?.isNotBlank() == true) {
                            itemBinding.btnConfirm.setText("取消确认")
                        }

                        itemBinding.btnConfirm.setOnClickListener {
                            if (itemBinding.btnConfirm.text == "确认件数") {
                                val number = itemBinding.tvOrderStatus.text.toString()
                                val lhbz = itemBinding.tvluhaobz.text.toString()
                                val lh = itemBinding.tvluhao1.text.toString()
                                netProgressDialog.showDialog()
                                mThreadPool.submit {
                                    confirmNumberOnNet(checkWeightCarBeans[i].pcbm, number, lhbz,lh)
                                }
                            } else if (itemBinding.btnConfirm.text == "取消确认") {
                                mThreadPool.submit {
                                    cancelConfirmNumberOnNet(checkWeightCarBeans[i].pcbm)
                                }
                            }
                        }

                        if (checkWeightCarBeans[i].wxbz.isNotBlank()) {
                            // 无效出厂
                            itemBinding.btnConfirm.isGone = true
                        }
                    }
                }
            }
        } catch (e: Exception) {
            runOnUiThread {
                netProgressDialog.dismiss()
            }
        }
    }

    private fun confirmNumberOnNet(pcbm: String, num: String, lhbz: String, lh: String) {
        val method = "get_ShouChiConfirm"
        val envolopeVersion = SoapEnvelope.VER11
        val soapAction = "http://tempuri.org/get_ShouChiConfirm"
        val request = SoapObject(Constant.nameSpace, method)
        request.addProperty("pcbm", pcbm)
        request.addProperty("num", num)
        request.addProperty("lhbz", lhbz)
        request.addProperty("lh", lh)
        val envelope = SoapSerializationEnvelope(envolopeVersion)
        envelope.setOutputSoapObject(request)
        envelope.dotNet = true
        val se = HttpTransportSE(Constant.urlCheckWeight)
        try {
            se.call(soapAction, envelope) //envolopeVersion为ver12第一个参数可以为空，必须接口支持ver12才行
            val response = envelope.bodyIn as SoapObject
            //response的处理需要根据返回的具体情况，基本都要进行下面一步
            Timber.e(response.toString())
            val responseSoapObject = response.getProperty("get_ShouChiConfirmResult").toString()
            val resultBean = Gson().fromJson(responseSoapObject, ResultBean::class.java)
            Timber.e(responseSoapObject)
            runOnUiThread {
                if (resultBean.state == "1") {
                    toast("确认成功！")
                    setResult(RESULT_OK)
                    finish()
                } else {
                    toast("确认失败！")
                }
                netProgressDialog.dismiss()
            }

        } catch (e: Exception) {
            e.printStackTrace()
            runOnUiThread {
                netProgressDialog.dismiss()
            }
        }
    }

    private fun cancelConfirmNumberOnNet(pcbm: String) {
        val method = "get_ShouChiCancle"
        val envolopeVersion = SoapEnvelope.VER11
        val soapAction = "http://tempuri.org/get_ShouChiCancle"
        val request = SoapObject(Constant.nameSpace, method)
        request.addProperty("pcbm", pcbm)
        val envelope = SoapSerializationEnvelope(envolopeVersion)
        envelope.setOutputSoapObject(request)
        envelope.dotNet = true
        val se = HttpTransportSE(Constant.urlCheckWeight)
        try {
            se.call(soapAction, envelope) //envolopeVersion为ver12第一个参数可以为空，必须接口支持ver12才行
            val response = envelope.bodyIn as SoapObject
            //response的处理需要根据返回的具体情况，基本都要进行下面一步
            Timber.e(response.toString())
            val responseSoapObject = response.getProperty("get_ShouChiCancleResult").toString()
            val resultBean = Gson().fromJson(responseSoapObject, ResultBean::class.java)
            Timber.e(resultBean.toString())
            runOnUiThread {
                if (resultBean.state == "1") {
                    toast("取消成功！")
                    setResult(RESULT_OK)
                    finish()
                } else {
                    toast("取消失败！")
                }
                netProgressDialog.dismiss()
            }

        } catch (e: Exception) {
            e.printStackTrace()
            runOnUiThread {
                netProgressDialog.dismiss()
            }
        }
    }

    private fun getShouChiWuXiao(pcbm: String, reason: String, opperson: String) {
        val method = "get_ShouChiWuXiao"
        val envolopeVersion = SoapEnvelope.VER11
        val soapAction = "http://tempuri.org/get_ShouChiWuXiao"
        val request = SoapObject(Constant.nameSpace, method)
        request.addProperty("pcbm", pcbm)
        request.addProperty("reason", reason)
        request.addProperty("opperson", opperson)
        val envelope = SoapSerializationEnvelope(envolopeVersion)
        envelope.setOutputSoapObject(request)
        envelope.dotNet = true
        val se = HttpTransportSE(Constant.urlCheckWeight)
        try {
            se.call(soapAction, envelope) //envolopeVersion为ver12第一个参数可以为空，必须接口支持ver12才行
            val response = envelope.bodyIn as SoapObject
            //response的处理需要根据返回的具体情况，基本都要进行下面一步
            Timber.e(response.toString())
            val responseSoapObject = response.getProperty("get_ShouChiWuXiaoResult").toString()
            val resultBean = Gson().fromJson(responseSoapObject, ResultBean::class.java)
            Timber.e(resultBean.toString())
            runOnUiThread {
                if (resultBean.state == "1") {
                    toast("无效出厂成功！")
                    setResult(RESULT_OK)
                    finish()
                } else {
                    toast(resultBean.msg)
                }
                netProgressDialog.dismiss()
            }

        } catch (e: Exception) {
            e.printStackTrace()
            runOnUiThread {
                netProgressDialog.dismiss()
            }
        }
    }

//    private fun beSureLoadAmountOnNet(
//        itemBinding: ViewArrivalConfirmationBinding,
//        number: String,
//        C_DELIVERY_ID: String
//    ) {
//        mService.beSureLoadAmount(
//            userAccount,
//            soCode,
//            C_DELIVERY_ID,
//            number
//        )
//            .enqueue(object : Callback<String> {
//                @RequiresApi(Build.VERSION_CODES.M)
//                override fun onResponse(
//                    call: Call<String>,
//                    response: Response<String>
//                ) {
//                    if (response.isSuccessful) {
//                        val result = response.body()
//                            ?.let { parseResultXMLWithPull(it) }
//                        if (result != null && result.resultCode == "0") {
//                            itemBinding.btnConfirm.setBackgroundColor(
//                                resources.getColor(
//                                    R.color.teal_700,
//                                    theme
//                                )
//                            )
//                            itemBinding.btnConfirm.text = "取消确认"
//                            itemBinding.tvOrderStatus.isEnabled =
//                                false
//                        } else {
//                            result?.let {
//                                toast(it.resultMsg)
//                            }
//                        }
//                    }
//                }
//
//                override fun onFailure(
//                    call: Call<String>,
//                    t: Throwable
//                ) {
//                    Timber.e(t)
//                    toast("确认失败！")
//                }
//            })
//    }


    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.tvRightMenu -> {
                hideKeyboard()
                val dialog = AlertDialog.Builder(this).create()
                dialog.show()
                val window = dialog.window
                window?.clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM)
                val dialogBinding = DialogInvalidGrowthBinding.inflate(layoutInflater)
                window?.setContentView(dialogBinding.root)
                dialogBinding.tvTypeText.isGone = true
                dialogBinding.spinInvalid.isGone = true
                dialogBinding.etRemark.run {
                    isFocusableInTouchMode = true
                    isFocusable = true
                    requestFocus()
                }
                dialogBinding.etRemark.postDelayed({
                    showInputMethod()
                }, 200)
                dialogBinding.tvCancel.setOnClickListener {
                    hideKeyboard()
                    dialog.dismiss()
                }
                dialogBinding.tvConfirm.setOnClickListener {
                    val remark = dialogBinding.etRemark.text.toString()
                    if (remark.isBlank()) {
                        toast("请输入备注")
                        return@setOnClickListener
                    }

                    dialog.dismiss()

                    netProgressDialog.showDialog()
                    mThreadPool.submit {
                        if (mLists.isNotEmpty()) {
                            getShouChiWuXiao(mLists[0].pcbm, remark, userAccount)
                        }
                    }

                }
//                dialogBinding.spinInvalid.adapter = ArrayAdapter(
//                    this,
//                    R.layout.spinner_select_text,
//                    R.id.tvCarNum,
//                    mWuXiaoLists
//                )
//                dialogBinding.spinInvalid.onItemSelectedListener =
//                    object : AdapterView.OnItemSelectedListener {
//                        override fun onItemSelected(
//                            parent: AdapterView<*>?,
//                            view: View?,
//                            position: Int,
//                            id: Long
//                        ) {
//                            dialogBinding.etRemark.text =
//                                Editable.Factory.getInstance().newEditable(mWuXiaoLists[position])
//                            dialogBinding.etRemark.setSelection(dialogBinding.etRemark.text.length)
//                        }
//
//                        override fun onNothingSelected(parent: AdapterView<*>?) {
//                        }
//
//                    }

                if (mLists.isNotEmpty() && mLists[0].wxbz.isNotBlank()) {
                    dialogBinding.spinInvalid.isEnabled = false
                    dialogBinding.tvCancel.isGone = true
                    dialogBinding.tvConfirm.isGone = true
                    dialogBinding.tvLine2.isGone = true
                    dialogBinding.etRemark.text =
                        Editable.Factory.getInstance().newEditable(mLists[0].bz)

                }

            }
            R.id.btnLook -> {
                startActivity(
                    Intent(this, LookBarCodeActivity::class.java).putExtra(
                        "code",
                        soCode
                    )
                )
            }
            else -> Timber.e("click no view")
        }
    }

}